#include "btn_timer.h"

typedef enum
{
  USER_BUTTON_SW2 = 0,
  USER_BUTTON_SW3,
  USER_BUTTON_MAX
} user_button_t;

static flex_button_t user_button[USER_BUTTON_MAX];

volatile uint8_t sw2_clicked_flag = 0, sw3_clicked_flag = 0;

static uint8_t common_btn_read(void* arg)
{
  uint8_t value = 0;

  flex_button_t* btn = (flex_button_t*)arg;

  switch(btn->id)
  {
  case USER_BUTTON_SW2:
    value = gpio_input_data_bit_read(GPIOB, GPIO_PINS_5);
    break;
  case USER_BUTTON_SW3:
    value = gpio_input_data_bit_read(GPIOB, GPIO_PINS_4);
    break;
  default:
    break;
  }

  return value;
}

static void common_btn_evt_cb(void* arg)
{
  flex_button_t* btn = (flex_button_t*)arg;

//  printf("id: [%d - %s]  event: [%d - %30s]  repeat: %d\n",
//         btn->id, "id",
//         btn->event, "event",
//         btn->click_cnt);
  if(btn->event == FLEX_BTN_PRESS_CLICK && btn->id == USER_BUTTON_SW2)
  {
    sw2_clicked_flag = 1;
  }
  if(btn->event == FLEX_BTN_PRESS_CLICK && btn->id == USER_BUTTON_SW3)
  {
    sw3_clicked_flag = 1;
  }
}

void TMR3_GLOBAL_IRQHandler(void)
{
  if(tmr_flag_get(TMR3, TMR_OVF_FLAG) != RESET)
  {
    tmr_flag_clear(TMR3, TMR_OVF_FLAG);
    flex_button_scan();
  }
}

void user_button_init(void)
{
  int i;
  gpio_init_type gpio_initsturct = {0};
  crm_periph_clock_enable(CRM_GPIOB_PERIPH_CLOCK, TRUE);
  gpio_default_para_init(&gpio_initsturct);
  // BUTTON
  gpio_initsturct.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
  gpio_initsturct.gpio_mode = GPIO_MODE_INPUT;
  gpio_initsturct.gpio_out_type = GPIO_OUTPUT_PUSH_PULL;
  gpio_initsturct.gpio_pins = GPIO_PINS_4 | GPIO_PINS_5;
  gpio_initsturct.gpio_pull = GPIO_PULL_UP;
  gpio_init(GPIOB, & gpio_initsturct);

  crm_periph_clock_enable(CRM_TMR3_PERIPH_CLOCK, TRUE);

  /* tmr11 configuration */
  /* time base configuration */
  tmr_base_init(TMR3, 199, (192000000 / 10000) - 1);
  tmr_cnt_dir_set(TMR3, TMR_COUNT_UP);

  tmr_flag_clear(TMR3, TMR_OVF_FLAG);
  /* overflow interrupt enable */
  tmr_interrupt_enable(TMR3, TMR_OVF_INT, TRUE);
  nvic_irq_enable(TMR3_GLOBAL_IRQn, 4, 0);

  for(uint8_t i = 0; i < USER_BUTTON_MAX; i ++)
  {
    user_button[i].id = i;
    user_button[i].usr_button_read = common_btn_read;
    user_button[i].cb = common_btn_evt_cb;
    user_button[i].pressed_logic_level = 0;
    user_button[i].short_press_start_tick = FLEX_MS_TO_SCAN_CNT(1500);
    user_button[i].long_press_start_tick = FLEX_MS_TO_SCAN_CNT(3000);
    user_button[i].long_hold_start_tick = FLEX_MS_TO_SCAN_CNT(4500);

    flex_button_register(&user_button[i]);
  }
  /* enable tmr11 */
  tmr_counter_enable(TMR3, TRUE);
}